<?php
namespace Tongcheng\Controller;
use Think\Controller;
class IndexController extends CommonController {
    public function index(){
//        $sd['is'] = '122';
//        $sd['dd'] = '12122';
//        $sd['uid'] = I('uid');
//        $file =  I('file');
//        $code = $_FILES['file'];
//        if(is_array($code)){
//            foreach ($code as $file){
//                $fileName = $this->upload($file);
//                if(!empty($fileName)){
//                    $sd['filename'] = $fileName;
//                    $sd['index'] = I('index');
//                }
//            }
//        }else{
//            $fileName = $this->upload($code);
//            $sd['filename'] = $fileName;
//            $sd['index'] = I('index');
//        }
//        $this->ajaxReturn(json_encode($sd),'JSON');
//        exit();
        $this->display();
    }

    public function menu(){
        $this->display();
    }


    public function upload($code){
        date_default_timezone_set("Asia/Shanghai"); //设置时区
        if(is_uploaded_file($_FILES['file']['tmp_name'])) {
            //把文件转存到你希望的目录（不要使用copy函数）
            $uploaded_file=$_FILES['file']['tmp_name'];
            $username = "min_img";
            //我们给每个用户动态的创建一个文件夹
            $user_path=$_SERVER['DOCUMENT_ROOT']."/m_pro/".$username;
            //判断该用户文件夹是否已经有这个文件夹
            if(!file_exists($user_path)) {
                mkdir($user_path);
            }
            //$move_to_file=$user_path."/".$_FILES['file']['name'];
            $file_true_name=$_FILES['file']['name'];
            $newfilename = time().rand(1,1000)."-".date("Y-m-d").substr($file_true_name,strrpos($file_true_name,"."));
            $move_to_file=$user_path."/".$newfilename;//strrops($file_true,".")查找“.”在字符串中最后一次出现的位置
            //echo "$uploaded_file   $move_to_file";
            if(move_uploaded_file($uploaded_file,$move_to_file)) {
                return 'http://'.$_SERVER['HTTP_HOST'].'/m_pro/min_img/'.$newfilename;
            } else {
                return null;
            }
        } else {
            return null;
        }

    }

    // public function test(){
    //     $json = file_get_contents("https://www.58zltc.com/Public/layui/lay/modules/areas.json");
    //     $td = json_decode($json, 1);

    //     foreach ($td as $key => $value) {
    //         $new['city_code'] = $value['id'];
    //         $new['city_name'] = $value['areaname'];
    //         $new['pid'] = $value['parentid'];

    //         $new1['pid'] = M("City")->add($new);

    //         foreach ($value['child'] as $k => $v) {
    //             $new1['city_code'] = $v['id'];
    //             $new1['city_name'] = $v['areaname'];
    //             $new2['pid'] = M("City")->add($new1);
    //             foreach ($v['child'] as $idx => $item) {
    //                 $new2['city_code'] = $item['id'];
    //                 $new2['city_name'] = $item['areaname'];
    //                 echo M("City")->add($new2)."<br/>";
    //             }
    //         }
    //     }
    //     // dump($td);
    // }

    public function gobal(){
    	$map['wid'] = session('wid');
    	$model = M("Wechat");
    	if(IS_AJAX){
            if(I('post.sheng') == 0){
                $new['city'] = 0;
            }elseif(I('post.shi') == 0){
                $new['city'] = I('post.sheng');
            }elseif(I('post.xian') == 0){
                $new['city'] = I('post.shi');
            }else{
                $new['city'] = I('post.xian');
            }

            if(I("yong") < 0 || I("yong") > 100){
                $this->error('佣金比例必须大于等于0、小于等于100');
            }
            if(I("withdraw_rate") < 0 || I("withdraw_rate") > 100){
                $this->error('提现抽成比例必须大于等于0、小于等于100');
            }
    		$new['app_id'] = I('post.app_id');
    		$new['app_secret'] = I('post.app_secret');
            $new['tongcheng_fee'] = I('post.tongcheng_fee');
//            $new['shop_fee'] = I('post.shop_fee');
            $new['yong'] = I("post.yong");
            $new['withdraw_rate'] = I("post.withdraw_rate");
            $new['withdraw_rate1'] = I("post.withdraw_rate1");
    		$model->where($map)->save($new);
    		$this->success("修改成功！");
    	}else{
    		$info = $model->where($map)->find();
    		$this->assign('info',$info);

            if($info['city'] == 0){
                $arr = [0,0,0];
            }else{
                $eq['city_code'] = $info['city'];
                $city = M("City")->where($eq)->find();
                if($city['pid'] != 0){
                    $eq1['id'] = $city['pid'];
                    $pcity = M("City")->where($eq1)->find();
                    if($pcity['pid'] != 0){
                        $eq1['id'] = $pcity['pid'];
                        $pcode = M("City")->where($eq1)->getField('city_code');
                        $arr = [$pcode, $pcity['city_code'], $info['city']];
                    }else{
                        $arr = [$pcity['city_code'], $info['city'], 0];
                    }
                }else{
                    $arr = [$info['city'], 0, 0];
                }
            }
            $this->assign('arr',json_encode($arr));
    		$this->display();
    	}
    }

    public function pay(){
    	$map['wid'] = session('wid');
    	$model = M("Wechat");
    	if(IS_AJAX){
    		$new['mch_id'] = I('post.mch_id');
    		$new['partner_key'] = I('post.partner_key');
            $model->where($map)->save($new);
//            if (I('file')) {
//                $uploads_dir = '../../../ThinkPHP/Library/Vendor/Weixinpay/certificate/';
//                $format = substr(I('file'),strrpos(I('file'), '.'));
//                $name = md5(I('file'));
//                $suc = move_uploaded_file(I('file'), $uploads_dir.$name.$format);
//                var_dump($_FILES);
//                $suc ? $this->success("修改成功！") : '';
//            }
            $this->success("修改成功！");
    		// echo $model->getLastSql();
    	}else{
    		$info = $model->where($map)->find();
    		$this->assign('info',$info);
    		$this->display();
    	}
    }
    //获取模板消息页面
    public function template(){
        $map['wid']=session('wid');
        $list = M('form')->where($map)->select();
        //处理cotent内容
        foreach($list as $k=>$v){
            $list[$k]['content'] = explode("}}",$v['content']);
            array_pop($list[$k]['content']);
        }
        if(IS_AJAX){
           getTemplate();
        }
        $this->assign("list",$list);
        $this->display();
    }


    //展示24小时拼团失败退单记录
    public function refundList()
    {
        $wid = session('wid');
        $count = M('refund')
            ->alias('r')
            ->join('tp_order o on o.id = r.orderid')
            ->join('tp_user u on u.openid = o.openid')
            ->where(array('r.wid'=>$wid ))
            ->count();
        $page = new \Think\Page($count, 20);
        $show = $page->show();
        $info = M('refund')
            ->alias('r')
            ->field('r.*,u.nickname')
            ->join('tp_order o on o.id = r.orderid')
            ->join('tp_user u on u.openid = o.openid')
            ->where(array('r.wid'=>$wid ))
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        $this->assign('info',$info);
        $this->assign('show',$show);
        $this->assign('count',$count);
        $this->display();
    }

    public function fabu(){

        //生成小程序。判断是否授权，没有则跳转至授权页面
        $shop_id = I("shop_id");
        $eq['shop_id'] = $shop_id;
        $mini = M('wechat')->where($eq)->find();
        if(!$mini){
            $this->redirect(U("Home/Index/index",array('shop_id'=>$shop_id)));

        }
        $map['wid'] = session('wid');
        $model = M("Wechat");
        $info = $model->where($map)->find();

        $authorizer_access_token = $this->getAccessToken($info);

        $res = $this->ihttp_get("https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token={$authorizer_access_token}");
        $td = json_decode($res, true);
        // dump($td);
        if($td['status'] == 2){
            $this->redirect("step3");
        }
        if(isset($td['status']) && $td['status'] === 0){
            $this->ihttp_post("https://api.weixin.qq.com/wxa/release?access_token={$authorizer_access_token}", "{}");
        }

        $url = "https://api.weixin.qq.com/wxa/modify_domain?access_token={$authorizer_access_token}";
        if($_GET['type'] == 'set'){
            $post_data = array(
                "action"=>'set',
                "requestdomain"=>array("https://www.58zltc.com",'https://apis.map.qq.com','https://tls.qcloud.com','https://webim.tim.qq.com'),
                "wsrequestdomain"=>array("wss://socket.58zltc.com"),
                "uploaddomain"=>array("https://www.58zltc.com"),
                "downloaddomain"=>array("https://www.58zltc.com"));
        }else{
            $post_data = array("action"=>'get');
        }
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['errcode'] !== 0){
            $this->reAuth();
        }

        $vo['requestdomain'] = implode(',', $td['requestdomain']);
        $vo['wsrequestdomain'] = implode(',', $td['wsrequestdomain']);
        $vo['uploaddomain'] = implode(',', $td['uploaddomain']);
        $vo['downloaddomain'] = implode(',', $td['downloaddomain']);
        $this->assign('vo',$vo);
        $this->assign('shop_id',$shop_id);
        $this->display('step1');
    }

    public function step2(){
        //shop_id 生成小程序用
        $shop_id = I("shop_id");
        $shop = M("shop")->where(['shop_id'=>$shop_id])->find();
        $model = M("Wechat");
        $map['wid'] = session('wid');
        if($shop_id){
            $wid =M('wechat')->where(['shop_id'=>$shop_id])->find();
            $map['wid'] = $wid?$wid['wid']:session('wid');
        }
        $info = $model->where($map)->find();
        if($shop_id){
            switch($shop['type']){
                case " ":
                    $template_id = 174;
                    $user_desc = "通用";
                    break;
                case "":
                    $template_id = 174;
                    $user_desc = "通用";
                    break;
                case "jiaoyu":
                    $template_id =171;
                    $user_desc = "教育";
                    break;
                case "car":
                    $template_id = 170;
                    $user_desc = "汽车";
                    break;
                case "jiancai":
                    $template_id =169;
                    $user_desc = "建材";
                    break;
            }
        }else{
            if($info['shop_id']){
                $info2 =M("shop")->where(['shop_id'=>$info['shop_id']])->find();
                switch($info2['type']){
                    case " ":
                        $template_id = 174;
                        $user_desc = "通用";
                        break;
                    case "":
                        $template_id = 174;
                        $user_desc = "通用";
                        break;
                    case "jiaoyu":
                        $template_id =171;
                        $user_desc = "教育";
                        break;
                    case "car":
                        $template_id = 170;
                        $user_desc = "汽车";
                        break;
                    case "jiancai":
                        $template_id =169;
                        $user_desc = "建材";
                        break;
                }
            }else{
                //$template_id = 136;
                //$template_id = 177;
                $template_id = 195;
            }
        }

        $authorizer_access_token = $this->getAccessToken($info);
        $url = "https://api.weixin.qq.com/wxa/commit?access_token={$authorizer_access_token}";

        $ext = array(
            "extEnable" => true,
            'ext'=>array(
                "host" => "https://www.58zltc.com",
                'appid'=>$info['appid'],
            ),
            'window'=>array(
                'navigationBarTitleText'=>$info['nick_name']
            )
        );
        $ext_json = json_encode($ext, JSON_UNESCAPED_UNICODE);

        $post_data = array(
                "template_id"=>$template_id,
                "ext_json"=>$ext_json,
                "user_version"=>date("Y-m-d",time()),
                "user_desc"=>$user_desc);

        // if($_SESSION['uid'] == 1 || $_SESSION['uid'] == 2){
        //     $post_data = array(
        //         "template_id"=>66,
        //         "ext_json"=>$ext_json,
        //         "user_version"=>"V0.9.6",
        //         "user_desc"=>"测试版本");
        // }
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['errcode'] !== 0){
            // if($td['errcode'] == 40001 || $td['errcode'] == 50001 || $td['errcode'] == 61007){
            //     $this->reAuth();
            // }
            // $this->error($td['errmsg']);
            $this->reAuth();
        }
        $this->assign('shop_id',$shop_id);
        $this->assign('code_url',U('get_code_img')."?access_token={$authorizer_access_token}");

        $this->display('step2');
    }
    //模块管理
    public function modular()
    {
        if(IS_AJAX){
            $data['order'] = I('order');
            $eq['id'] = I('id');
            M('tui')->where($eq)->save($data);
            $this->success("修改成功");
        } else {
            $tui = M("tui")->where(['type'=>'index'])->select();

            $this->assign('list',$tui);
            $this->display();
        }

    }

    //
    public function editModularStatus () {
        $model = M("tui");
        $map['id'] = $_POST['id'];
        $arr = $model->where($map)->find();
        $arr['status'] ? $save['status'] = 0 : $save['status'] = 1;
        $row = $model->where($map)->save($save);
        $row ? $this->success("修改成功！") : $this->error("网络忙，请稍后再试！");
    }

    public function get_code_img(){
        $authorizer_access_token = $_GET['access_token'];
        $code_url = "https://api.weixin.qq.com/wxa/get_qrcode?access_token={$authorizer_access_token}";

        $res = $this->ihttp_get($code_url);

        header("Content-type:image/jpeg;");
        echo $res;
    }

    public function step3(){
        $shop_id = I("shop_id");
        if($_GET['type'] == 'set'){
            $map['wid'] = session('wid');
            if($shop_id){
                $wid =M('wechat')->where(['shop_id'=>$shop_id])->find();
                $map['wid'] = $wid?$wid['wid']:session('wid');
            }
            $model = M("Wechat");
            $info = $model->where($map)->find();
            $shop = M("shop")->where(['shop_id'=>$info['shop_id']])->find();
            switch($shop['type']){
                case " ":
                    $pages = "pages/shop/detail";
                    $title = "通用";
                    break;
                case "":
                    $pages = "pages/shop/detail";
                    $title = "通用";
                    break;
                case "jiaoyu":
                    $pages = "pages/jiaoyu/detail";
                    $title = "教育";
                    break;
                case "car":
                    $pages = "pages/car/detail";
                    $title = "汽车";
                    break;
                case "jiancai":
                    $pages = "pages/jiancai/detail";
                    $title = "建材";
                    break;
            }
            $authorizer_access_token = $this->getAccessToken($info);
            $url = "https://api.weixin.qq.com/wxa/get_category?access_token={$authorizer_access_token}";
            $res = $this->ihttp_get($url);
            $td = json_decode($res, true);

            // dump($td);
            if($td['errcode'] !== 0){
                $this->error($td['errmsg']);
            }
            if(count($td['category_list']) == 0){
                $this->error('请登录微信官方小程序后台设置服务类目！');
            }
            $cate = $td['category_list'][0];

            $url = "https://api.weixin.qq.com/wxa/submit_audit?access_token={$authorizer_access_token}";

            $post_data = array(
                "item_list"=>array(
                    array(
                        "address"=>$pages?$pages:"pages/index/index",
                        "tag"=>"生活,同城",
                        "first_class"=>$cate['first_class'],
                        "second_class"=>$cate['second_class'],
                        "first_id"=>$cate['first_id'],
                        "second_id"=>$cate['second_id'],
                        "title"=>$title?$title:"首页",
                    )
                )
            );

            $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);

            // dump($json);
            // exit();
            $res = $this->ihttp_post($url, $json);
            $td = json_decode($res, true);
            if($td['errcode'] !== 0){
                $this->error($td['errmsg']);
            }
            $this->redirect("step3");
        }else{
            $this->display('step3');
        }
    }

    private function reAuth(){
        $appid = C("OPEN_APPID");
        $pre_auth_code = A("Home/Index")->get_pre_auth_code();

        // $pre_auth_code = $pre_auth_code."KG5F";
        $redirect_uri = urlencode("https://www.58zltc.com?type=reset");
        $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$appid}&pre_auth_code={$pre_auth_code}&redirect_uri={$redirect_uri}";
        $this->error('没有相应的权限，请重新授权！', $url);
    }  


    private function getAccessToken($info){
        if(date("Y-m-d H:i:s") < $info['token_end_time']){
            return $info['authorizer_access_token'];
        }else{
            $token = $this->get_component_access_token();
            $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$token}";
            $post_data = array(
                "component_appid"=>C("OPEN_APPID"),
                "authorizer_appid"=>$info['appid'],
                "authorizer_refresh_token"=>$info['authorizer_refresh_token']);
            $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
            $res = $this->ihttp_post($url, $json);
            $td = json_decode($res, true);
            if($td['authorizer_access_token']){
                $map['wid'] = $info['wid'];
                $data['authorizer_access_token'] = $td['authorizer_access_token'];
                $data['authorizer_refresh_token'] = $td['authorizer_refresh_token'];
                $data['token_end_time'] = date("Y-m-d H:i:s", time()+$td['expires_in']-60);
                M("Wechat")->where($map)->save($data);
                return $td['authorizer_access_token'];
            }else{
                // dump($td);
                // $this->error($td['errmsg']);
                $this->reAuth();
            }
        }
    }

    private function get_component_access_token(){
        $token = S("component_access_token");
        if($token){
            return $token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";

        $post_data = array(
            "component_appid"=>C("OPEN_APPID"),
            "component_appsecret"=>C("OPEN_APPSECRET"),
            "component_verify_ticket"=>S("component_verify_ticket"));
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['component_access_token']){
            S("component_access_token", $td['component_access_token'], $td['expires_in'] - 120);
            return $td['component_access_token'];
        }else{
            return false;
        }
    }

    //拼团24小时不成功自动退款
    public function refundTuanMoney()
    {
        $map['wid'] = session();
    }

    //
    public function paySub () {
        $map['wid'] = session('wid');
        $model = M("Wechat");
        $new['mch_id'] = $_POST['mch_id'];
        $new['partner_key'] = $_POST['partner_key'];

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        //$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload();
        //print_r($info);exit;
        if(!$info) {// 上传错误提示错误信息
            //$this->error($upload->getError());
        } else {// 上传成功
            if ($info['file']) {
                $path = './Uploads/'.$info['file']['savepath']. $info['file']['savename'];
                $new['certificate_path_cert'] = $path;
            }
            if ($info['file_2']) {
                $path_key = './Uploads/'.$info['file_2']['savepath']. $info['file_2']['savename'];
                $new['certificate_path_key'] = $path_key;
            }
        }
        $model->where($map)->save($new);
        $this->success("修改成功！");
    }
    public function cateNav(){
        if(IS_AJAX){
            $model = M("index_cate");
            $map['wid'] = session('wid');
            $res['count'] = $model->where($map)->count();
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:10;
            $res['list'] = $model->where($map)->order("add_time desc")->page("{$page},{$limit}")->select();
            foreach($res['list'] as $key=>$value){
                $time = date("Y-m-d H:i:s",$value['add_time']);
                $res['list'][$key]['add_time'] = $time;
            }

            $this->ajaxReturn($res);
        }else{
            $this->display();
        }
    }
    public function cateAdd(){
        if(IS_AJAX){
            $model = M("index_cate");
            $new['wid'] = session('wid');
            $new['name'] = I('post.name');
            $new['status'] = I('post.status');
            $new['add_time'] = time();

            if(empty($new['name'])){
                $this->error('请输入分类名称！');
            }
            if($model->add($new)){
                $this->success('添加成功！');
            }else{
                $this->error('网络忙，请稍后再试！');
            }
        }else{
            $this->display();
        }
    }
    public function cateEdit(){
        $model = M("index_cate");
        $map['id'] = $_GET['id'];

        if(IS_AJAX){
            $new['name'] = I('post.name');
            $new['status'] = I('post.status');

            if(empty($new['name'])){
                $this->error('请输入标题！');
            }
            $model->where($map)->save($new);
            $this->success('修改成功！');
        }else{
            $vo = $model->where($map)->find();

            $this->assign('vo',$vo);
            $this->display('cateAdd');
        }
    }
    public function cateDel(){
        $model = M("index_cate");
        $map['wid'] = session('wid');
        $map['id'] = $_POST['id'];

        if($model->where($map)->delete()){
            $this->success("删除成功！");
        }else{
            $this->error("网络忙，请稍后再试！");
        }
    }
}